package com.example.tangjiangxu.fragmentdemo2;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

public class BackStackActivity extends Activity implements TwoFragment.OnClickTwoButtonListener, OneFragment.OnClickOneButtonListener{
    private static final String TAG = "BackStackActivity";
    private OneFragment oneFragment;
    private TwoFragment twoFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_backstatck);

        addOneFragment();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_fragment3, menu);
        return true;
    }

    private void addOneFragment() {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        OneFragment oneFragment = new OneFragment();
        fragmentTransaction.add(R.id.fragment_content, oneFragment, "One");
        //第一个Fragment不应该加入到回退栈中，否则当前Fragment返回会显示白屏
        // fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    /**
     * 点击了OneFragment中的按钮，跳转TowFragment
     */
    @Override
    public void onClickOneButton() {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        twoFragment = new TwoFragment();
        //注册OnClickTwoButtonListener对象到TwoFragment中，用于回调
        twoFragment.setOnClickTwoButtonListener(this);
        //这里使用replace方式调用加载了TowFragment,相当于remove然后add, 所以会调用OneFragment的onDestoryView方法，即销毁OneFragment的视图
        //当TowFragment加入到回退栈后,回退到OneFragment时，会调用onCreateView,重新创建视图
        fragmentTransaction.replace(R.id.fragment_content, twoFragment, "Two");
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    /**
     * 点击了OneFragment中的按钮，跳转TowFragment
     */
    @Override
    public void onClickTwoButton() {
        Log.e(TAG, "onClickTwoButton: ");
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        //这里使用hide隐藏了TwoFragment,并用add方法加载上了ThreeFragment, 这时候不会调用TwoFragment的onDestoryView, 即不会销毁TwoFragment上的视图
        fragmentTransaction.hide(twoFragment);
        ThreeFragment threeFragment = new ThreeFragment();
        fragmentTransaction.add(R.id.fragment_content, threeFragment, "three");
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
}
